package com.example.core.network

import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory

/**
 * Created by zhudongao
 * Desc
 * Date 2020/10/24
 */
object MoshiHelper {

    val moshi:Moshi = Moshi.Builder()
        .addLast(KotlinJsonAdapterFactory())
        .build()

    /**
     * json string解析
     */
    inline fun <reified T> fromJson(json:String):T? {
        return moshi.adapter(T::class.java).fromJson(json)
    }

    /**
     * 将对象转换成
     */
    inline fun <reified T> toJson(t: T): String {
        return moshi.adapter(T::class.java).toJson(t)
    }

    /**
     * 将json list string转换为对象列表
     */
    inline fun <reified T> listFromJson(json: String): List<T> {
        val type = Types.newParameterizedType(List::class.java, T::class.java)
        return moshi.adapter<List<T>>(type).fromJson(json) ?: emptyList()
    }

    /**
     * 将json list string转换为对象列表
     */
    inline fun <reified T> listToJson(data: List<T>): String {
        val type = Types.newParameterizedType(List::class.java, T::class.java)
        return moshi.adapter<List<T>>(type).toJson(data)
    }
}